package com.objk.admin.security.hander;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.obj.commpont.common.utils.WebUtils;
import com.obj.commpont.common.vo.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权访问时的处理方案
 *
 * @author yuan 2018/4/22 22:13
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (!response.isCommitted()) {
            //request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
            //response.setStatus(HttpStatus.FORBIDDEN.value());
            if (WebUtils.isAjax(request)) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(ServerResponse.createByErrorMessage("无权访问")));
            } else {
                response.setContentType("text/html");
                response.setCharacterEncoding("utf-8");

                RequestDispatcher dispatcher = request.getRequestDispatcher("/403.html");
                dispatcher.forward(request, response);
            }
        }
    }
}
